package com.soda.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.soda.bean.Course;
import com.soda.bean.Industry;
import com.soda.bean.Information;
import com.soda.bean.News;
import com.soda.bean.Notice;
import com.soda.bean.Student;
import com.soda.bean.Survey;
import com.soda.service.CourseServiceHan;
import com.soda.service.InformationServiceHan;
import com.soda.service.NoticeService;
import com.soda.service.QianTaiCourseServiceYu;
import com.soda.service.impl.CourseServiceHanImpl;
import com.soda.service.impl.InformationServiceHanImpl;
import com.soda.service.impl.NoticeServiceImpl;
import com.soda.service.impl.QianTaiCourseServiceYuImpl;
import com.soda.util.PageInfo;

public class ShowQianTaiServletYu extends HttpServlet {

	CourseServiceHan csh = new CourseServiceHanImpl();
	InformationServiceHan is = new InformationServiceHanImpl();
	NoticeService ns = new NoticeServiceImpl();
	QianTaiCourseServiceYu qt = new QianTaiCourseServiceYuImpl();

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String meet = request.getParameter("meet");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();

		// =================首页显示的内容==========================================================

		if (meet == null) {

			List<Information> list2 = is.getSelectAll();
			request.setAttribute("informations", list2);
			List<Course> list1 = csh.getAllSelect();
			request.setAttribute("course", list1);
			List<Notice> notice = ns.getSelectAll();
			request.setAttribute("notices", notice);

			// 在线课程
			List<Course> list = qt.selectZaiXianCourseNameByCouType(0);
			request.setAttribute("course2", list);

			// 动态新闻
			List<News> news = qt.selectNewsTitleByCouName();
			request.setAttribute("news", news);

			// 行业信息
			List<Industry> ind = qt.selectIndustryTitleByIndName();
			request.setAttribute("industry", ind);

			// survey
			List<Survey> sur = qt.selectSurveyContent();
			request.setAttribute("survey", sur);

			request.getRequestDispatcher("qiantai/index.jsp").forward(request,
					response);
			return;
		}

		/**
		 ************************** 显示动态新闻里面的内容**************************
		 * 
		 */
		if ("dongnews".equals(meet)) {
			String newsId = new String(request.getParameter("newsId").getBytes(
					"ISO-8859-1"), "UTF-8");

			News news = qt.selectNewseByNewsName(Integer.parseInt(newsId));

			request.setAttribute("news", news);
			request.getRequestDispatcher("qiantai/info.jsp").forward(request,
					response);
			return;
		}

		/**
		 ************************** 显示 公告信息里面的内容**************************
		 * 
		 */

		if ("notice".equals(meet)) {
			String notid = new String(request.getParameter("notid").getBytes(
					"ISO-8859-1"), "UTF-8");

			Notice notice = qt.selectNoticeByNewsName(Integer.parseInt(notid));

			request.setAttribute("notice", notice);
			request.getRequestDispatcher("qiantai/notices.jsp").forward(
					request, response);
			return;
		}

		/**
		 ************************** 显示 行业信息里面的内容**************************
		 * 
		 */
		if ("industry".equals(meet)) {
			String indid = new String(request.getParameter("indid").getBytes(
					"ISO-8859-1"), "UTF-8");

			Industry industry = qt.selectIndustryByNewsName(Integer
					.parseInt(indid));

			request.setAttribute("industry", industry);
			request.getRequestDispatcher("qiantai/industry.jsp").forward(
					request, response);
			return;
		}

		/**
		 * 显示CourseInfo
		 */
		// ==================课程名字超链接里面的的内容================================================

		if ("courseInfo".equals(meet)) {
			
			//获得
			String couid = request.getParameter("ci");

			// courseInfo
			Course course = qt.getCourseInfoBycouName(Integer.parseInt(couid));
			request.setAttribute("course", course);
			request.getRequestDispatcher("qiantai/courseInfo.jsp").forward(
					request, response);
			return;
		}

		/**
		 * **************************显示在线视频和现场课程里面的课程***************************
		 * *
		 */

		if ("course".equals(meet) || "1".equals(meet) || "0".equals(meet)) {
			String couName = null;
			String couType = null;
			String couname = null;

			if (request.getParameter("couName") != null) {
				couName = new String(request.getParameter("couName").getBytes(
						"ISO-8859-1"), "UTF-8");
			}
			if (request.getParameter("couType") != null) {
				couType = new String(request.getParameter("couType").getBytes(
						"ISO-8859-1"), "UTF-8");
			}
			// 获取header.jsp传过来的内容
			if (request.getParameter("couname") != null) {
				couname = new String(request.getParameter("couname").getBytes(
						"ISO-8859-1"), "UTF-8");
			}
			if ("0".equals(meet)) {
				// 现场课程
				couType = "1";
			}
			if ("1".equals(meet)) {
				// 在线视频
				couType = "0";
			}

			if ("请输入课程名称".equals(couname)|| "".equals(couname)) {

				PageInfo pi = new PageInfo(1, 10, 0, 0);// page ,per ,LastPage
														// ,total
				// 查询现场课程   或者在线视频的课程总条数(包括模糊查询)
				int total = qt.getTotalCount(Integer.parseInt(couType));
				
				pi.setTotal(total);// 这里面就计算了最后一页即总页数

				String page = request.getParameter("page");
				if (page != null) {
					pi.setPage(Integer.parseInt(page));
				}
				
				List<Course> list = qt.selectAllCourseByCouName(Integer.parseInt(couType),pi.getPage(), pi.getPer());
				
				request.setAttribute("names", list);
				request.setAttribute("page", pi);
				
				if ("0".equals(couType)) {
					request.getRequestDispatcher("qiantai/video.jsp").forward(
							request, response);
				}
				if ("1".equals(couType)) {
					request.getRequestDispatcher("qiantai/xianchang.jsp").forward(
							request, response);
				}

				return;
				

			}

			PageInfo pi = new PageInfo(1, 10, 0, 0);// page ,per ,LastPage
													// ,total
			// 查询课程总条数(包括模糊查询)
			int total = qt.getTotalCount(couName, couname,
					Integer.parseInt(couType));
			pi.setTotal(total);// 这里面就计算了最后一页即总页数

			String page = request.getParameter("page");
			if (page != null) {
				pi.setPage(Integer.parseInt(page));
			}

			// chachacha
			List<Course> list = qt.selectZaiXianCourseByCouName(couName,
					pi.getPage(), pi.getPer(), couname,
					Integer.parseInt(couType));

			// 查询完把这些一起set，然后转发
			request.setAttribute("names", list);
			request.setAttribute("page", pi);
			request.setAttribute("nam", couName);
			request.setAttribute("couname", couname);
			if ("0".equals(couType)) {
				request.getRequestDispatcher("qiantai/video.jsp").forward(
						request, response);
			}
			if ("1".equals(couType)) {
				request.getRequestDispatcher("qiantai/xianchang.jsp").forward(
						request, response);
			}

			return;
		}

		/**
		 * ******************购买在线视频 这时候 就需要判断有没有登录
		 * 如果没有登录直接让其跳转到登录界面!******************
		 */

		if ("goumai".equals(meet)) {

			// 获取登录学生的信息
			Student student = (Student) request.getSession().getAttribute(
					"student");

			// 若没有登录 直接跳转登录
			if (student == null) {
				out.print("<script type='text/javascript'> location.href='qiantai/login.jsp';</script>");
				return;
			}
			/**
			 * 若登录，点击报名或者购买的时候，如果没有选中任何的课程，需要有必要的提示信息。如果选中的课程中，自己已经报名或者购买，
			 * 那么就要提示已经购买。前者都满足的情况下才能够进行报名，或者购买
			 */

			// 获取video.jsp里面js传的参数Array 例如:10,11,12 是couID的数组
			String couIds = request.getParameter("Array");
			// 将couIds转化成数组
			String[] couId = couIds.split(",");

			/**
			 * 判断'我的未结算课程 ' 和'我的课程'里面有没有 有的话 就会在未结算课程显示并且不能再添加 没有的话
			 * 不会再为结算课程里面显示并且能添加 还有判断这可课程是否下架没下架
			 */
			for (int i = 0; i < couId.length; i++) {
				int state = qt.selectCourseStateByStuCourseId(
						Integer.parseInt(couId[i]), student.getStuId());

				if (state == 0) {
					out.print("<script>alert('对不起,您选择课程里可能有未结算的！');</script>");
					out.print("<script>location.href='ShowQianTaiServletYu?meet=weijiesuan';</script>");
					return;
				}
				if (state == 1) {
					out.print("<script>alert('对不起,您的课程里面已经有这门课！');</script>");
					out.print("<script>location.href='ShowQianTaiServletYu?meet=MyCourse';</script>");
					return;
				}
			}
			// 判断课程下架否?
			for (int i = 0; i < couId.length; i++) {
				Course co = qt.selectCourseByStucouId(Integer
						.parseInt(couId[i]));

				if (co.getCouState() == 2 || co.getCouState() == 4) {
					out.print("<script>alert('对不起,您所选的课程里可能有已下架的课程！');</script>");
					out.print("<script>location.href='history.back();';</script>");
					return;
				}

			}

			/**
			 * 先不拦截
			 */
			// 获取这个学生的中间表课程信息
			List<Course> stucous = qt.selectCousFromStuCourseByStuId(student
					.getStuId());
			for (int i = 0; i < couId.length; i++) {
				// 根据课程ID添加课程
				Course co = qt.selectInfoOfCourseBycouId(Integer
						.parseInt(couId[i]));

				stucous.add(co);

				// 增加中间信息
				qt.updateCoustateByCouid(Integer.parseInt(couId[i]), student);
			}

			request.getRequestDispatcher("ShowQianTaiServletYu?meet=weijiesuan")
					.forward(request, response);

		}
		// ==================未结算里面的内容==========================================================

		/**
		 * 未结算课程里面的内容
		 */
		if ("weijiesuan".equals(meet) || "3".equals(meet)) {

			// 获取登录人
			Student student = (Student) request.getSession().getAttribute(
					"student");

			if (student == null) {
				out.print("<script type='text/javascript'> location.href='qiantai/login.jsp';</script>");
				return;
			}

			// 获取搜索传过来的模糊未结算里面的模糊内容
			String couname = request.getParameter("couname");
			PageInfo pi = new PageInfo(1, 10, 0, 0);
			// 查询我的未结算课程总条数
			int total = qt.getWeiJieCourseTotalCount(student.getStuId(),
					couname);

			pi.setTotal(total);

			// 根据总条数计算总页数
			pi.setLastPage((total + pi.getPer() - 1) / pi.getPer());
			// 上一页下一页 哈哈哈
			String pa = request.getParameter("page");
			if (pa != null) {
				pi.setPage(Integer.parseInt(pa));
			}
			// 查询中间表里未结算的课程根据(包括模糊)

			List<Course> list = qt.selectWeiJieSuanCourseByPage(
					student.getStuId(), couname, pi.getPage(), pi.getPer());

			request.setAttribute("course", list);
			request.setAttribute("page", pi);
			request.setAttribute("couname", couname);
			request.getRequestDispatcher("qiantai/pay.jsp").forward(request,
					response);

		}
		/**
		 * ******************************我的课程******************************
		 */
		if ("MyCourse".equals(meet) || "2".equals(meet)) {

			// 获取登录学生的信息
			Student student = (Student) request.getSession().getAttribute(
					"student");
			if (student == null) {
				out.print("<script type='text/javascript'> location.href='qiantai/login.jsp';</script>");
				return;
			}
			

			// 获取搜索传过来的模糊内容
			String couName = request.getParameter("couname");
			// 条件查询我的课程里面的总条数 放在一起写 如果有条件就带着条件查询 没有就不带 不用判断couName是不是空的
			
			
			
			PageInfo pi = new PageInfo(1, 10, 0, 0);
			// 查询我的课程总条数
			int total = qt.selectCondiTotalCount(couName, student.getStuId());
			pi.setTotal(total);

			// 根据总条数计算总页数
			pi.setLastPage((total + pi.getPer() - 1) / pi.getPer());

			String pa = request.getParameter("page");
			if (pa != null) {
				pi.setPage(Integer.parseInt(pa));
			}

			// 根据学生的ID 在stu_course表里面查询我的课程666666666666
			List<Course> list = qt.selectCourseOfBughtById(student.getStuId(),
					couName, pi.getPage(), pi.getPer());

			request.setAttribute("course", list);
			request.setAttribute("page", pi);
			request.setAttribute("couName", couName);
			request.getRequestDispatcher("qiantai/course.jsp").forward(request,
					response);

		}
		/**
		 * ************************结算的时候要判断些什么？******************************
		 */
		if ("jiesuan".equals(meet)) {

			// 获取登录人
			Student student = (Student) request.getSession().getAttribute(
					"student");
			String couIds = request.getParameter("Array");
			// 将couIds转化成数组
			String[] couId = couIds.split(",");
			PageInfo pi = new PageInfo(1, 10, 0, 0);

			int totMoney = 0;
			for (int i = 0; i < couId.length; i++) {
				Course cou = qt.selectInfoOfCourseBycouId(Integer
						.parseInt(couId[i]));

				totMoney += cou.getCouMoney();
				if (totMoney > student.getStuMoney()) {
					out.print("<script>alert('余额不足，请充值');</script>");
					out.print("<script type='text/javascript'> location.href='qiantai/chongzhi.jsp';</script>");
					return;
				}
			}
			for (int i = 0; i < couId.length; i++) {
				Course cou = qt.selectInfoOfCourseBycouId(Integer
						.parseInt(couId[i]));
				// 设置学生的余额 里面的余额
				student.setStuMoney(student.getStuMoney() - cou.getCouMoney());
				// 更该数据库里学生的钱数
				qt.updateStuMoneyByStuId(student.getStuId(),
						student.getStuMoney());
				// 更改中间表中这门课这门课的状态为已购买
				qt.updateCourseFromStuCourseStateByCouId(Integer
						.parseInt(couId[i]));
			}

			out.print("<script type='text/javascript'> location.href='ShowQianTaiServletYu?meet=MyCourse';</script>");

			return;
		}
		// ===================取消未结算===============================
		if ("quxiao".equals(meet)) {
			// 获取登录人
			Student student = (Student) request.getSession().getAttribute(
					"student");
			String couIds = request.getParameter("Array");
			// 将couIds转化成数组
			String[] couId = couIds.split(",");

			for (int i = 0; i < couId.length; i++) {
				qt.deleteInfoOfCourseBycouId(Integer.parseInt(couId[i]));

			}
			out.print("<script type='text/javascript'> location.href='ShowQianTaiServletYu?meet=weijiesuan';</script>");
			return;
		}


	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
